package com.shenmazong.service.impl;

import cn.hutool.db.nosql.redis.RedisDS;
import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenmazong.config.RedisKeyUtils;
import com.shenmazong.entity.TbCounter;
import com.shenmazong.mapper.TbCounterMapper;
import com.shenmazong.service.TbCounterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.vo.ListParamVo;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.Set;

/**
 * <p>
 * 文章数据表  ——>  John 服务实现类
 * </p>
 *
 * @author 还怕大雨吗
 * @since 2021-09-18
 */
@Service
@Slf4j
public class TbCounterServiceImpl extends ServiceImpl<TbCounterMapper, TbCounter> implements TbCounterService {

    @Resource
    private TbCounterMapper tbCounterMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;


    /***
     * @description 查询自己的所有点赞与浏览
     * @params [userID]
     * @return com.shenmazong.utils.ResultResponse
     * @author -还怕大雨吗
     * @date 2021/9/18 14:40
     */
    @Override
    @Cacheable(value = "selectCounter")
    public ResultResponse selectCounter(Long userID) {
        ListParamVo  ts =  tbCounterMapper.selectOnley(userID);
        return ResultResponse.SUCCESS(ts);
    }

    /***
     * @description 实现点赞
     * @params [articId, userId]
     * @return com.shenmazong.utils.ResultResponse
     * @author -还怕大雨吗
     * @date 2021/9/26 10:12
     */
    @Override
    public ResultResponse insertCounterUser(String articId, String userId) {
        if (StringUtils.isEmpty(articId) || StringUtils.isEmpty(userId)){
            return ResultResponse.SUCCESS("网络繁忙，请稍后重试");
        }
        String userKey = RedisKeyUtils.getUserKey(articId, userId);
        Boolean aBoolean = stringRedisTemplate.opsForHash().hasKey(articId + "", userKey);
        if (aBoolean == true){
            stringRedisTemplate.opsForHash().increment(articId+"",userKey,-1);
            stringRedisTemplate.opsForHash().delete(articId,userKey);
            return ResultResponse.SUCCESS("取消成功");
        }
        stringRedisTemplate.opsForHash().put(articId+"",userKey,1+"");
        rabbitTemplate.convertAndSend("givez",articId+":"+userId);
        return ResultResponse.SUCCESS("点赞成功");
    }

    @Override
    public ResultResponse selectCounterUser(String articId) {
        Set<Object> keys = stringRedisTemplate.opsForHash().keys(articId + "");
        return ResultResponse.SUCCESS(keys.size());
    }


}
